package com.springboot.auth.authorization.exception;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * Created by ZengJian on 2021/2/3 0003 上午 9:22
 */
public class CustomOauthExceptionSerializer extends StdSerializer<CustomOauthException> {
    public CustomOauthExceptionSerializer() {
        super(CustomOauthException.class);
    }

    @Override
    public void serialize(CustomOauthException value, JsonGenerator gen, SerializerProvider provider) throws IOException {
//        HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        gen.writeStartObject();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        gen.writeObjectField("success", false);
        gen.writeObjectField("code", value.getResult().getCode());
        gen.writeObjectField("status", value.getHttpErrorCode());
        gen.writeObjectField("message", value.getMessage());
        gen.writeObjectField("path", request.getServletPath());
        gen.writeObjectField("time", value.getResult().getTime());
        gen.writeObjectField("mesg", value.getResult().getMesg());
        if (value.getAdditionalInformation() != null) {
            for (Map.Entry<String, String> entry : value.getAdditionalInformation().entrySet()) {
                String key = entry.getKey();
                String add = entry.getValue();
                gen.writeObjectField(key, add);
            }
        }
        gen.writeEndObject();
//        gen.writeObject(value.getResult());

        // 最新
//        gen.writeStartObject();
//        gen.writeStringField("error",String.valueOf(value.getHttpErrorCode()));
//        gen.writeStringField("message",value.getMessage());
//        gen.writeStringField("path",request.getServletPath());
//        gen.writeStringField("timestamp",String.valueOf(System.currentTimeMillis()));
//        if(value.getAdditionalInformation()!=null){
//            for(Map.Entry<String,String> entry:value.getAdditionalInformation().entrySet()){
//            String key=entry.getKey();
//            String add=entry.getValue();
//            gen.writeStringField(key,add);
//            }
//        }
//        gen.writeEndObject();


    }
}
